package com.zk.mylib.func.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.zk.mylib.R;

/**
 *
 */
public class HomeDragView extends ConstraintLayout {
    protected int screenWidth;
    protected int screenHeight;
    protected int lastX;
    protected int lastY;
    private int oriLeft;
    private int oriRight;
    private int oriTop;
    private int oriBottom;
    private int initY;
    private int dragDirection;
    private static final int BOTTOM = 1;
    /**
     * 滑动工具类
     */
    private Scroller mScroller;
    private VelocityTracker mVelocityTracker;
    private int mTouchSlop;
    /**
     * 最小的FLING速度
     */
    private static final int FLING_VELOCITY_MIN = 600;
    private int childHeight;

    /**
     * 初始化获取屏幕宽高
     */
    protected void initScreenW_H() {
        screenHeight = getResources().getDisplayMetrics().heightPixels - 40;
        screenWidth = getResources().getDisplayMetrics().widthPixels;
    }

    public HomeDragView(Context context) {
        this(context, null);
    }

    public HomeDragView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HomeDragView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initScreenW_H();
        final ViewConfiguration configuration = ViewConfiguration.get(context);
        mTouchSlop = configuration.getScaledTouchSlop();
        mScroller = new Scroller(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(ev);
        int action = ev.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            oriLeft = getLeft();
            oriRight = getRight();
            oriTop = getTop();
            oriBottom = getBottom();
            lastY = (int) ev.getRawY();
            lastX = (int) ev.getRawX();
            initY = (int) ev.getRawY();
            dragDirection = getDirection(this, (int) ev.getX(),
                    (int) ev.getY());
        }
        // 处理拖动事件
        delDrag(this, ev, action);
        invalidate();
//        if (dragDirection == BOTTOM) {
//            requestLayout();
//        }
        return dragDirection == BOTTOM;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return getDirection(this, (int) ev.getX(),
                (int) ev.getY()) == BOTTOM;
    }

    /**
     * 处理拖动事件
     * 
     * @param v
     * @param event
     * @param action
     */
    protected void delDrag(View v, MotionEvent event, int action) {
        switch (action) {
        case MotionEvent.ACTION_MOVE:
            int dx = (int) event.getRawX() - lastX;
            int dy = (int) event.getRawY() - lastY;
            switch (dragDirection) {
            case BOTTOM: // 下边缘
                bottom(v, dy);
                ViewGroup.LayoutParams layoutParams = getLayoutParams();
                layoutParams.height = oriBottom - oriTop;
                setLayoutParams(layoutParams);

//                v.layout(oriLeft, oriTop, oriRight, oriBottom);
//                v.requestLayout();
                break;
            }
            lastX = (int) event.getRawX();
            lastY = (int) event.getRawY();
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_CANCEL:
            onActionUp();
            dragDirection = 0;
            if (mVelocityTracker != null) {
                mVelocityTracker.clear();
                mVelocityTracker.recycle();
                mVelocityTracker = null;
            }
            break;
        }
    }

    private void onActionUp() {
        if (dragDirection != BOTTOM) {
            dragDirection = 0;
            return;
        }
        mVelocityTracker.computeCurrentVelocity(1000);
        float velocity = mVelocityTracker.getYVelocity();
        if (Math.abs(velocity) > FLING_VELOCITY_MIN) {
            // 根据手势速度判断消隐
            if (velocity > 0) {
                slideDown();
            } else {
                slideUp();
            }
        } else {
            // 根据距离判断消隐
//            float y = mSlidingView.getTranslationY();
            float y = lastY - initY;
            float showY = childHeight * 0.25f;
            if (Math.abs(y) > showY) {
                if (y > 0) {
                    slideDown();
                } else {
                    slideUp();
                }
            } else {
                // 达不到滑动距离，回弹回去
                if (y > 0) {
                    slideUp();
                } else {
                    slideDown();
                }
            }
        }

    }

    private void slideDown() {
        System.out.println("=============slideDown");
//        mScroller.startScroll(0, oriBottom, 0, dy, 200);
//        invalidate();
//        mIsSlideDown = true;
//        bottom(v, dy);
//        v.layout(oriLeft, oriTop, oriRight, oriBottom);
    }

    private void slideUp() {
        System.out.println("=============slideUp");
    }

    @Override
    public void computeScroll() {
        if (dragDirection == BOTTOM) {
            if (mScroller.computeScrollOffset()) {
//                if (mSlidingView != null) {
//                    int targetY = mScroller.getCurrY();
//                    mSlidingView.setTranslationY(targetY);
//                    mSlidingView.setAlpha(clipTargetAlpha(mSlidingView, targetY));
//                }
                invalidate();
            } else {
//                if (mSlideMode == FLING_MODE_UP) {
//                    if (mSlidingView != null) {
//                        mSlidingView.setVisibility(View.GONE);
//                    }
//                } else {
//                    if (mSlidingDownListener != null) {
//                        mSlidingDownListener.onShow(this);
//                    }
//                }
//                mTouchMode = TOUCH_MODE_RESET;
//                mSlideMode = FLING_MODE_RESET;
            }
        }
    }

    private int mMaxBottom = -1;
    /**
     * 触摸点为下边缘
     * 
     * @param v
     * @param dy
     */
    private void bottom(View v, int dy) {
        oriBottom += dy;
        if (oriBottom > screenHeight) {
            oriBottom = screenHeight;
        }
        int minBottom = 20;
        int count = getChildCount();
        if (count > 0) {
//            minBottom = getChildAt(0).getMeasuredHeight();
        }

        RecyclerView view = getChildAt(0).findViewById(R.id.recyclerview);
        int parentHeight = getChildAt(0).getMeasuredHeight();
        childHeight = view.getMeasuredHeight();
        minBottom = parentHeight - childHeight;
        int maxBottom = parentHeight;
        boolean reachBottom = view.canScrollVertically(1) || view.canScrollVertically(-1);
        System.out.println("========childHeight=====  " + mMaxBottom + "   " + parentHeight + "  " + childHeight + "  " + (oriBottom - oriTop) + "  " + reachBottom);
        if (reachBottom) {
            mMaxBottom = parentHeight;
        }
        if (oriBottom - oriTop < minBottom) {
            oriBottom = minBottom + oriTop;
        } else if (oriBottom - oriTop > mMaxBottom) {
            if (!reachBottom) {
                oriBottom = mMaxBottom + oriTop;
            }
        }
    }


    /**
     * 获取触摸点flag
     * 
     * @param v
     * @param x
     * @param y
     * @return
     */
    protected int getDirection(View v, int x, int y) {
        int bottom = v.getBottom();
        int top = v.getTop();
        int touchHeight = 120;
        System.out.println("======================= " + (bottom - top - y) + "   " + touchHeight);
        if (bottom - top - y < touchHeight) {
            return BOTTOM;
        }
        return 0;
    }

}